import path from 'path'
import { fileURLToPath } from 'url'
import dataSql from './data_manager_sqlite.js'
import { makeKey } from './common-lib/keys.js'
import { dataDir, shopDataPath, questDataPath, relationshipDataPath } from './common-lib/paths.js'
import * as cache from './cache.js'
import { getFileLockIntegration } from './FileLockIntegration.js'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const fileLock = getFileLockIntegration()

async function readJsonAsync (filePath, defaultValue = null) {
  try {
    return await fileLock.readJSON(filePath, defaultValue)
  } catch { return defaultValue }
}

async function writeJsonAsync (filePath, data) {
  try {
    await fileLock.writeJSON(filePath, data, { space: 2 })
    return true
  } catch { return false }
}

const rarityEmojiMap = {
  common: '⭐',
  uncommon: '⭐⭐',
  rare: '⭐⭐⭐',
  epic: '⭐⭐⭐⭐',
  legendary: '⭐⭐⭐⭐⭐'
}

const itemIconMap = {
  weapon: '🗡️',
  armor: '🛡️',
  material: '🧪',
  consumable: '🧃',
  misc: '🎁'
}

class TextHelper {
  static getShopData () {
    // 使用双层缓存
    const key = makeKey('shop', 'list')
    return (async () => {
      const cached = await cache.get(key)
      if (cached) return Array.isArray(cached) ? cached : []
      const data = await readJsonAsync(shopDataPath, [])
      const list = Array.isArray(data) ? data : []
      await cache.set(key, list, 5 * 60 * 1000)
      return list
    })()
  }

  static async getUserLevel (userId, groupId) {
    try {
      const home = await dataSql.getUserHome?.(userId, groupId)
      if (home && typeof home.level === 'number') return home.level
    } catch {}
    return 0
  }

  static async getUserMoney (userId, groupId) {
    try {
      const home = await dataSql.getUserHome?.(userId, groupId)
      if (home && typeof home.money === 'number') return home.money
    } catch {}
    return 0
  }
  static async getUserData (userId, groupId) {
    const money = await TextHelper.getUserMoney(userId, groupId)
    // 任务数据优先从SQLite获取
    let quest = null
    try { quest = await dataSql.getQuest?.(userId, groupId) } catch {}
    if (!quest) {
      quest = await readJsonAsync(path.join(dataDir, 'user_quest', `${groupId || 'global'}_${userId}.json`), {})
    }
    const points = typeof quest?.points === 'number' ? quest.points : 0
    return { money, points }
  }

  static async getSigninData (userId, groupId) {
    const res = await dataSql.getSignIn(userId, groupId)
    return res || { todaySigned: false, streak: 0 }
  }

  static async getSignInStreak (userId, groupId) {
    const res = await dataSql.getSignIn(userId, groupId)
    return Number(res?.streak || 0)
  }


  static async updateSignInStreak (userId, groupId, newValue) {
    await dataSql.setSignIn(userId, groupId, Number(newValue) || 0)
    return true
  }

  static async getUserInventory (userId, groupId) {
    try {
      const inv = await dataSql.loadUserInventory?.(userId, groupId)
      return Array.isArray(inv) ? inv : []
    } catch {}
    return []
  }

 
  static async updateUserInventory (userId, groupId, newInventory) {
    try {
      if (Array.isArray(newInventory)) {
        await dataSql.saveUserInventory?.(userId, groupId, newInventory)
        return true
      }
    } catch {}
    return false
  }

  
  static async addToInventory (userId, groupId, item) {
    const inv = await TextHelper.getUserInventory(userId, groupId)
    inv.push(item)
    return await TextHelper.updateUserInventory(userId, groupId, inv)
  }

  
  static async removeFromInventory (userId, groupId, predicate) {
    const inv = await TextHelper.getUserInventory(userId, groupId)
    const filtered = inv.filter(i => !predicate(i))
    return await TextHelper.updateUserInventory(userId, groupId, filtered)
  }

  
  static getSynthesisRarityEmoji (rarity) {
    const key = String(rarity || '').toLowerCase()
    return rarityEmojiMap[key] || '⭐'
  }

  static getRarityEmoji (rarity) {
    return TextHelper.getSynthesisRarityEmoji(rarity)
  }

  static getItemIcon (type) {
    const key = String(type || '').toLowerCase()
    return itemIconMap[key] || '📦'
  }

  
  static async getUserWorkshop (userId, groupId) {
    try {
      const data = await dataSql.getWorkshop(userId, groupId)
      return data || { level: 1, slots: 1 }
    } catch {
      return { level: 1, slots: 1 }
    }
  }

  static async saveUserWorkshop (userId, groupId, data) {
    await dataSql.saveWorkshop(userId, groupId, data)
    return true
  }

  
  static async recordSynthesis (userId, groupId, record) {
    const list = await TextHelper.getSynthesisHistory(userId, groupId)
    list.push({ ...record, ts: Date.now() })
    return TextHelper.saveSynthesisHistory(userId, groupId, list)
  }

  static async getSynthesisHistory (userId, groupId) {
    try {
      const list = await dataSql.getSynthesisHistory(userId, groupId)
      return Array.isArray(list) ? list : []
    } catch { return [] }
  }

  static async saveSynthesisHistory (userId, groupId, list) {
    await dataSql.saveSynthesisHistory(userId, groupId, list)
    return true
  }

  static async autoRefreshShop () {
    const list = await TextHelper.getShopData()
    return Array.isArray(list) ? list : []
  }

  
  static async showCoupleRankingText (ranking) {
    const tpl = await readJsonAsync(relationshipDataPath, { templates: {} })
    const t = tpl.templates?.ranking || '排行榜'
    return `${t}: ${ranking || ''}`
  }

  static async showSingleStatusText (text) {
    // 关系文案改为异步读取以避免阻塞
    const tpl = await readJsonAsync(relationshipDataPath, { templates: {} })
    const t = tpl.templates?.single || '单身状态'
    return `${t}: ${text || ''}`
  }

  static async showLoveBankText (amount) {
    const tpl = await readJsonAsync(relationshipDataPath, { templates: {} })
    const t = tpl.templates?.lovebank || '恋爱银行'
    return `${t}: ${amount}`
  }

  static async showCoupleTaskText (taskText) {
    const tpl = await readJsonAsync(relationshipDataPath, { templates: {} })
    const t = tpl.templates?.couple_task || '情侣任务'
    return `${t}: ${taskText || ''}`
  }

  
  static async getLuckBoost (userId, groupId) {
    return await dataSql.getBoost(userId, groupId, 'luck')
  }

  static async getWorkBoost (userId, groupId) {
    return await dataSql.getBoost(userId, groupId, 'work')
  }

  static async consumeLuckBoost (userId, groupId, amount = 1) {
    return await dataSql.consumeBoost(userId, groupId, 'luck', amount)
  }

  static async consumeWorkBoost (userId, groupId, amount = 1) {
    return await dataSql.consumeBoost(userId, groupId, 'work', amount)
  }

  
  static async getRelationshipStatus (userId, groupId) {
    return await dataSql.getRelationship(userId, groupId)
  }

  static calculateDuelPower (userStats) {
    if (!userStats || typeof userStats !== 'object') return 0
    const atk = Number(userStats.attack || 0)
    const def = Number(userStats.defense || 0)
    const spd = Number(userStats.speed || 0)
    return Math.max(0, atk * 1.2 + def * 0.8 + spd * 0.5)
  }

  static showDuelResultText (result) {
    return `对决结果：${result?.summary || ''}`
  }

  static showProposeResultText (result) {
    return `求婚结果：${result?.summary || ''}`
  }
}

export default TextHelper
export { TextHelper }